import type { PiniaPluginContext } from 'pinia'
import { cloneDeep } from 'lodash-es'

export function piniaPersistedstate(context: PiniaPluginContext) {
  const {
    options: { persist = false },
    store,
    pinia,
  } = context

  // 判断是否需要持久化
  if (!persist) return

  // 暂存State
  let persistState = cloneDeep(store.$state)
  // 从缓存中读取
  const storageState = uni.getStorageSync(store.$id)
  if (storageState) {
    persistState = typeof storageState === 'string' ? JSON.parse(storageState) : storageState
  }
  store.$state = persistState
  store.$subscribe(() => {
    // 在存储变化的时候将store缓存
    uni.setStorageSync(store.$id, cloneDeep(store.$state))
  })
}

declare module 'pinia' {
  interface DefineStoreOptions<Id extends string, S extends StateTree, G, A> {
    persist?: boolean
  }
}
